<template>
	<view class="login-btn-box">
		<!-- #ifdef MP-WEIXIN -->
		<button v-if="canIUseGetUserProfile" @click="getUserProfile" class="login-btn primary-color"><slot name="lBtn">登录/注册</slot></button>
		<button v-else class="login-btn primary-color" open-type="getUserInfo" @getuserinfo="getuserinfo"><slot name="lBtn">登录/注册</slot></button>
		<!-- #endif -->
		<!-- #ifdef MP-TOUTIAO -->
		<button class="login-btn primary-color" @click="getuserinfoTT"><slot name="lBtn">登录/注册</slot></button>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS || H5 -->
		<button class="login-btn primary-color" @click="appLogin"><slot name="lBtn">去登录</slot></button>
		<!-- #endif -->
	</view>
</template>
 
<script>
export default {
	data() {
		return {
			userInfo: {},
			wxUserInfo: {},
			loginCode: '',
			provider: '',
			canIUseGetUserProfile: false
		};
	},
	created() {
		// #ifdef MP-WEIXIN
		if (!this.$common.isLogin()) {
			uni.login({
				provider: 'weixin',
				success: res => {
					this.loginCode = res.code;
				}
			});
		}
		this.canIUseGetUserProfile = !!uni.getUserProfile;
		// #endif
	},
	methods: {
		// APP登录
		appLogin() {
			// #ifdef APP-PLUS
			this.$emit('loginSuccess');
			const res = uni.getSystemInfoSync();
			if (res.platform === 'ios') {
				const iosAuditStatus = this.$store.state.iosAuditStatus;
				const isUpdate = uni.getStorageSync('isUpdate');
				if (iosAuditStatus === 4 && !isUpdate) {
					this.goPage('/pagesT/public/login');
				} else {
					this.goPage('/pagesT/public/wxLogin');
				}
			} else {
				this.goPage('/pagesT/public/wxLogin');
			}
			// #endif
			// #ifdef H5
			this.$emit('loginSuccess');
			this.goPage('/pagesT/public/wxLogin');
			// #endif
		},
		// 拒绝跳转主页面
		goIndex() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		// 头条
		getuserinfoTT() {
			uni.login({
				provider: 'toutiao',
				success: res => {
					uni.setStorageSync('loginCode', res.code);
					this.loginCode = res.code;
					uni.getUserInfo({
						provider: 'toutiao',
						success: prop => {
							console.log(prop);
							this.wxUserInfo = prop;
							// 用户图像
							const avator = prop.userInfo.avatarUrl;
							uni.setStorageSync('avator', avator);
							// 用户昵称
							const NickName = prop.userInfo.nickName;
							uni.setStorageSync('NickName', NickName);
							this.microappLogin(this.loginCode);
						}
					});
				}
			});
		},
		getUserProfile() {
			wx.getUserProfile({
				desc: '用于完善用户资料',
				lang: 'zh_CN',
				success: res => {
					console.log(res);
					console.log('获取用户授权信息成功');
					this.getuserinfo(res);
				},
				fail: fail => {
					console.log('获取用户授权信息失败');
				}
			});
		},
		// 允许获取信息 微信
		getuserinfo(val) {
			this.$emit('loginSuccess');
			this.wxUserInfo = val.detail || val;
			// 用户图像
			const avator = this.wxUserInfo.userInfo.avatarUrl;
			uni.setStorageSync('avator', avator);
			// 用户昵称
			const NickName = this.wxUserInfo.userInfo.nickName;
			uni.setStorageSync('NickName', NickName);
			if (!this.loginCode) {
				uni.login({
					provider: 'weixin',
					success: res => {
						this.loginCode = res.code;
						this.Login(this.loginCode);
					}
				});
			} else {
				this.Login(this.loginCode);
			}
		},
		// 头条小程序登陆
		microappLogin(code) {
			this.$u.api
				.microappLogin({
					code: code
				})
				.then(({ data }) => {
					uni.setStorageSync('openid', data.openid);
					this.checkBindMiniProgram(data.openid, '');
				});
		},
		// 微信小程序通过code获取openId
		Login(code) {
			uni.showLoading();
			this.$u.api
				.getOpenId({
					code: code
				})
				.then(data => {
					uni.hideLoading();
					// code 用过之后 清除缓存的code
					this.loginCode = '';
					if (!data.data.unionid) {
						this.decryptData(this.wxUserInfo.iv, this.wxUserInfo.encryptedData, data.data.openid);
					} else {
						uni.setStorageSync('openid', data.data.openid);
						uni.setStorageSync('unionid', data.data.unionid);
						this.checkBindMiniProgram(data.data.openid, data.data.unionid);
					}
					// this.checkBindMiniProgram(data.data.openid, data.data.unionid);
					// uni.setStorageSync('session_key', data.data.session_key);
				});
		},
		// 反解 unionId
		decryptData(iv, encryptedData, openid) {
			// const iv = e.detail.iv;
			// const encryptedData = e.detail.encryptedData;
			this.$u.api
				.decryptData({
					openid: openid,
					iv: iv,
					encryptedData: encryptedData
				})
				.then(data => {
					uni.setStorageSync('openid', openid);
					uni.setStorageSync('unionid', data.data.unionId);
					this.checkBindMiniProgram(openid, data.data.unionId);
				});
		},
		// 判断是否已绑定  checkBindMiniProgram
		checkBindMiniProgram(openid, unionid) {
			this.$u.api
				.checkBindMiniProgram({
					openId: openid || '',
					unionId: unionid || '',
					source: this.$common.source()
				})
				.then(async data => {
					// 如果返回空绑定手机
					if (!data.data.token) {
						setTimeout(() => {
							this.goPage(`/pagesT/binding/bindPhone`);
						}, 100);
						return;
					} else {
						const token = data.data.token;
						uni.setStorageSync('token', token);
						uni.setStorageSync('expireTime', data.data.expireTime);
						// 更新登录状态
						this.$store.commit('commit_hasLogin', true);
						// 添加分销上下级关系
						await this.relationshipBusinessman();
						// 否则验证审核
						await this.getCustomerInfo(data.data.token, data.data.expireTime);
					}
				});
		},
		// 添加分销上下级关系 source: 1:首次点击链接 2:首次下单 3:首次付款'
		async relationshipBusinessman() {
			if (!this.$store.state.businessmanId) {
				return;
			}
			this.$u.api
				.relationshipBusinessman({
					businessmanId: this.$store.state.businessmanId,
					source: 1
				})
				.then(res => {
					console.log('上下:', res);
				});
		},
		//先获取个人资料
		getCustomerInfo(token) {
			this.$u.api.getCustomerInfo().then(({ data }) => {
				if (data.enableStatus === 4) {
					uni.clearStorageSync();
					uni.showModal({
						title: '账号已被禁用，您可以',
						content: '联系电话：' + (data.enterpriseMobile||''),
						confirmText: '联系客服',
						cancelText: '取消',
						success: res => {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							} else {
								this.goPage('/pages/binding/bindInfo', 'reLaunch');
							}
						}
					});
					return;
				}
				// if (this.$store.state.baseSet.personnelReview === 5) {
				if (data.status === 3) {
					// uni.clearStorageSync();
					// 说明资料不完善，跳转到完善资料的页面
					uni.showModal({
						title: '审核未通过，请重新修改资料',
						content: data.auditFailReason || '',
						cancelText: '联系客服',
						confirmText: '修改资料',
						success: res => {
							if (res.confirm) {
								this.goPage('/pagesT/user/editUserInfo?token=' + token);
							} else if (res.cancel) {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							}
						}
					});
				} else if (data.status === 1) {
					// uni.clearStorageSync();
					uni.showModal({
						title: '账号正在审核中，您可以',
						content: '联系电话：' + (data.enterpriseMobile||''),
						confirmText: '先去逛逛',
						cancelText: '联系客服',
						success: res => {
							if (res.confirm) {
								this.goPage('/pages/index/index', 'switchTab');
							} else {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							}
						}
					});
				} else {
					this.$emit('loginFinish');
				}
			});
		}
	}
};
</script>

<style lang="scss">
.login-btn {
	font-size: 28rpx;
	// height: 40upx;
	line-height: inherit;
	background: transparent;
	color: $uni-color-primary;
	// width: 200upx;
	margin-left: 0;
	margin-right: 0;
	// display: inline-block;
}
.login-btn::after {
	border: 0 none;
}
</style>
